package com.sjgs.gis.service;


import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EurekaService {

    public List<InstanceInfo> getAppInstances(String appName) {
        List<Application> sortedApplications = getRegistry().getSortedApplications();
        ArrayList<Map<String, Object>> apps = new ArrayList<>();
        List<InstanceInfo> infos = new ArrayList<>();
        for (Application app : sortedApplications) {
            infos = app.getInstances().stream()
                    .filter(it->it.getAppName().toLowerCase().equals(appName.toLowerCase()))
                    .collect(Collectors.toList());
            for (InstanceInfo info : infos) {
                String appNamr = info.getAppName();
                String id = info.getId();
                String ipAddr = info.getIPAddr();
                String url = info.getStatusPageUrl();
                InstanceInfo.InstanceStatus status = info.getStatus();
                System.out.println(info.toString());
            }
        }
        return infos;
    }

    public List<Application> getApps() {
        return getRegistry().getSortedApplications();
    }

    private PeerAwareInstanceRegistry getRegistry() {
        return getServerContext().getRegistry();
    }

    private EurekaServerContext getServerContext() {
        return EurekaServerContextHolder.getInstance().getServerContext();
    }
}
